﻿using Microsoft.EntityFrameworkCore;
using Rechargeable.Games.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace Rechargeable.Games
{
    public class CardInfomationAppService : Rechargeable.RechargeableAppService, ICardInfomationAppService
    {

        private readonly IRepository<CardInformation, int> _repository;

        public CardInfomationAppService(IRepository<CardInformation, int> repository)
        {
            _repository = repository;
        }

        public async Task<CardInfomationDto> GetCard()
        {
            var cardInformation = await AsyncExecuter.FirstOrDefaultAsync((await _repository.GetQueryableAsync()).OrderBy(x => EF.Functions.Random()));
            if (cardInformation == null)
                return null;
            if (cardInformation.Number.ToLower().Contains("x") ||
                cardInformation.Name.Length < 2 ||
                cardInformation.Name.Length > 4 ||
                cardInformation.Number.Length != 18 ||
                CalculateAge(cardInformation.Number) < 18 ||
                CalculateAge(cardInformation.Number) > 60 ||
                IsChina(cardInformation.Name))
            {
                await _repository.DeleteAsync(cardInformation);
                return await GetCard();
            }

            return ObjectMapper.Map<CardInformation, CardInfomationDto>(cardInformation);
        }

        /// <summary>
        /// 根据出生日期，计算精确的年龄
        /// </summary>
        /// <param name="birthDate">生日</param>
        /// <returns></returns>
        private int CalculateAge(string number)
        {
            var birthDay = number.Substring(6, 4) + "-" + number.Substring(10, 2) + "-" + number.Substring(12, 2);
            DateTime birthDate = DateTime.Parse(birthDay);
            DateTime nowDateTime = DateTime.Now;
            int age = nowDateTime.Year - birthDate.Year;
            //再考虑月、天的因素
            if (nowDateTime.Month < birthDate.Month || (nowDateTime.Month == birthDate.Month && nowDateTime.Day < birthDate.Day))
            {
                age--;
            }
            return age;
        }

        private bool IsChina(string name)
        {
            char[] c = name.ToCharArray();
            bool flag = false;
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] >= 0x4e00 && c[i] <= 0x9fbb)
                {

                }
                else
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
    }
}
